package com.starsoft.frame.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.base.bean.BaseUser;
import com.starsoft.frame.base.bean.UserContext;
import com.starsoft.frame.base.service.UserService;
import com.starsoft.frame.util.SpringContext;
import com.starsoft.frame.util.StringUtil;

public class LoginFilter implements Filter{

	private final static Logger logger = LoggerFactory.getLogger(LoginFilter.class);// 日志
	
	private String[] ignores = new String[]{".js",".css",".html",".png",".gif",".jpg",".jpeg"};
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getRequestURI();
		for (String ignore : ignores) {
			if (url.endsWith(ignore)) {
				return true;
			}
		}
		// 排除登录页面
		if (url.contains("/base/login/")) {
			return true;
		}
		// 排除测试页面
		if (url.indexOf("/base/test/") > -1) {
			return true;
		}
		return false;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest) request;
		if (canIgnore(hrequest)) {
			chain.doFilter(request, response);
			return;
		}
		
		long startTime = System.currentTimeMillis();
		String path=hrequest.getServletPath();
		logger.info("Begin:"+path);
		//检验是否登录
		UserContext user=(UserContext)hrequest.getSession().getAttribute("user");
		if(user!=null && user instanceof UserContext){
			UserService.setUserContext(user);
			chain.doFilter(request, response);
		} else if(autoLogin(hrequest)){
			chain.doFilter(request, response);
		} else {
			HttpServletResponse hresponse=(HttpServletResponse) response;
			if(path.endsWith(".json")){
				hresponse.getWriter().append("{sucesse:'false',location:'"+hrequest.getContextPath()+"/base/login/login.jsp'}");	
			}else{
				hresponse.sendRedirect(hrequest.getContextPath()+"/base/login/login.jsp");
			}
		}
		long executeTime = System.currentTimeMillis() - startTime;
		logger.info("End  :"+path+" time:"+executeTime);
	}

	
	private boolean autoLogin(HttpServletRequest request){
		if(request==null || request.getCookies()==null){
			return false;
		}
		
		UserService us=SpringContext.getBean(UserService.class);
		String userName="";
		String userPwd="";
		String acountIdStr="";
		
		for (Cookie cookie : request.getCookies()) {
			if (cookie.getName().equals("userName")) {
				userName = cookie.getValue();
			}
			if (cookie.getName().equals("userPwd")) {
				userPwd = cookie.getValue();
			}
			if (cookie.getName().equals("acount")) {
				acountIdStr = cookie.getValue();
			}
		}
		BaseUser user = us.checkUser(userName, userPwd);
		if(user!=null){
			UserContext userContext = us.getUserContext(userName);
			request.getSession().setAttribute("user", userContext);
			try {
				if (!StringUtil.isEmpty(acountIdStr)) {
					Integer acountId = Integer.parseInt(acountIdStr);
					BaseAcount acount = us.getAcount(acountId);
					UserService.getUserContext().setAcount(acount);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		}
		return false;
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
